package com.ruoyi.foodworks.controller;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.foodworks.domain.CommentsLikes;
import com.ruoyi.foodworks.service.CommentsLikesService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import java.util.HashMap;

/**
 * 评论点赞Controller
 * 
 * @author ruoyi
 * @date 2025-08-12
 */
@RestController
@RequestMapping("/comments_likes/comments_likes")
public class CommentsLikesController extends BaseController
{
    @Autowired
    private CommentsLikesService commentsLikesService;

    /**
     * 查询评论点赞列表
     */
    @PreAuthorize("@ss.hasPermi('comments_likes:comments_likes:list')")
    @GetMapping("/list")
    public TableDataInfo list(CommentsLikes commentsLikes)
    {
        startPage();
        List<CommentsLikes> list = commentsLikesService.selectCommentsLikesList(commentsLikes);
        return getDataTable(list);
    }

    /**
     * 导出评论点赞列表
     */
    @PreAuthorize("@ss.hasPermi('comments_likes:comments_likes:export')")
    @Log(title = "评论点赞", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CommentsLikes commentsLikes)
    {
        List<CommentsLikes> list = commentsLikesService.selectCommentsLikesList(commentsLikes);
        ExcelUtil<CommentsLikes> util = new ExcelUtil<CommentsLikes>(CommentsLikes.class);
        util.exportExcel(response, list, "评论点赞数据");
    }

    /**
     * 获取评论点赞详细信息
     */
    @PreAuthorize("@ss.hasPermi('comments_likes:comments_likes:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return success(commentsLikesService.selectCommentsLikesById(id));
    }

    /**
     * 新增评论点赞
     */
    @PreAuthorize("@ss.hasPermi('comments_likes:comments_likes:add')")
    @Log(title = "评论点赞", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CommentsLikes commentsLikes)
    {
        return toAjax(commentsLikesService.insertCommentsLikes(commentsLikes));
    }

    /**
     * 修改评论点赞
     */
    @PreAuthorize("@ss.hasPermi('comments_likes:comments_likes:edit')")
    @Log(title = "评论点赞", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CommentsLikes commentsLikes)
    {
        return toAjax(commentsLikesService.updateCommentsLikes(commentsLikes));
    }

    /**
     * 删除评论点赞
     */
    @PreAuthorize("@ss.hasPermi('comments_likes:comments_likes:remove')")
    @Log(title = "评论点赞", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(commentsLikesService.deleteCommentsLikesByIds(ids));
    }
    
    /**
     * 评论点赞/取消点赞
     */
    @PostMapping("/like")
    public AjaxResult likeComment(@RequestBody Map<String, Object> params)
    {
        try {
            Integer commentId = (Integer) params.get("commentId");
            Integer userId = (Integer) params.get("userId");
            
            if (commentId == null || userId == null) {
                return AjaxResult.error("参数错误：commentId和userId不能为空");
            }
            
            // 检查用户是否已经点赞过这个评论
            CommentsLikes existingLike = commentsLikesService.selectCommentsLikesByUserAndComment(userId, commentId);
            
            if (existingLike != null) {
                // 已经点赞过，执行取消点赞（删除记录）
                int result = commentsLikesService.deleteCommentsLikesById(existingLike.getId());
                if (result > 0) {
                    // 获取更新后的点赞数
                    int likeCount = commentsLikesService.getCommentLikeCount(commentId);
                    Map<String, Object> responseData = new HashMap<>();
                    responseData.put("success", true);
                    responseData.put("action", "unlike");
                    responseData.put("likeCount", likeCount);
                    return AjaxResult.success("取消点赞成功", responseData);
                } else {
                    return AjaxResult.error("取消点赞失败");
                }
            } else {
                // 未点赞过，执行点赞（插入记录）
                CommentsLikes newLike = new CommentsLikes();
                newLike.setUserId(userId);
                newLike.setCommentId(commentId);
                newLike.setDel(0);
                
                int result = commentsLikesService.insertCommentsLikes(newLike);
                if (result > 0) {
                    // 获取更新后的点赞数
                    int likeCount = commentsLikesService.getCommentLikeCount(commentId);
                    Map<String, Object> responseData = new HashMap<>();
                    responseData.put("success", true);
                    responseData.put("action", "like");
                    responseData.put("likeCount", likeCount);
                    return AjaxResult.success("点赞成功", responseData);
                } else {
                    return AjaxResult.error("点赞失败");
                }
            }
        } catch (Exception e) {
            return AjaxResult.error("操作失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户对评论的点赞状态
     */
    @GetMapping("/like/status")
    public AjaxResult getLikeStatus(@RequestParam("commentIds") Integer[] commentIds, 
                                   @RequestParam("userId") Integer userId)
    {
        try {
            Map<String, Boolean> statusMap = new HashMap<>();
            for (Integer commentId : commentIds) {
                CommentsLikes like = commentsLikesService.selectCommentsLikesByUserAndComment(userId, commentId);
                statusMap.put(commentId.toString(), like != null);
            }
            return AjaxResult.success("获取成功", statusMap);
        } catch (Exception e) {
            return AjaxResult.error("获取失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取单个评论点赞数
     */
    @GetMapping("/like/count/{commentId}")
    public AjaxResult getCommentLikeCount(@PathVariable Integer commentId)
    {
        try {
            int count = commentsLikesService.getCommentLikeCount(commentId);
            return AjaxResult.success("获取成功", count);
        } catch (Exception e) {
            return AjaxResult.error("获取失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量获取评论点赞数
     */
    @GetMapping("/like/counts")
    public AjaxResult getCommentLikeCounts(@RequestParam("commentIds") Integer[] commentIds)
    {
        try {
            Map<String, Integer> countMap = new HashMap<>();
            for (Integer commentId : commentIds) {
                int count = commentsLikesService.getCommentLikeCount(commentId);
                countMap.put(commentId.toString(), count);
            }
            return AjaxResult.success("获取成功", countMap);
        } catch (Exception e) {
            return AjaxResult.error("获取失败：" + e.getMessage());
        }
    }
}
